package com.abel.bigwater.dataserver.model.qdies

import com.abel.bigwater.data.BcdString
import com.alibaba.fastjson.JSON
import com.fasterxml.jackson.databind.ObjectMapper
import io.netty.buffer.Unpooled
import org.joda.time.DateTime
import org.junit.Assert.*
import org.junit.Test
import org.slf4j.LoggerFactory

class D10LoginDataTest {

    @Test
    fun fill() {
        val data = D10LoginData().apply {
            address = BcdString(byteArrayOf(12, 0, 0, 1), true)
        }
        val buf = Unpooled.buffer().also { data.fill(it) }

        val hs = BcdString.hexString(buf)
        lgr.info(hs)
        assertEquals(hs, "49455344313012000001")
    }

    @Test
    fun parse() {
        val buf = Unpooled.buffer().writeBytes(BcdString.toByteArray(DEMO_STR))
        val d = D10LoginData()
        assert(d.parse(buf))

        lgr.info(ObjectMapper().writeValueAsString(d))
    }

    @Test
    fun fillAskState() {
        val buf = Unpooled.buffer()
        val p = D10Packet().apply {
            address = BcdString(byteArrayOf(12, 0, 0, 1), true)
            func = FuncType.AskState
            data = DtenAskStateData().also {
                it.time = DateTime(2012, 11, 3, 10, 20, 32)
                it.volt = 3.65F
                it.warnBcd = BcdString(ByteArray(20) { 0 }, true)
            }

            fill(buf)
        }

        val str = BcdString.create(buf, buf.readableBytes()).bcdString
        lgr.info(str)
        assertEquals(DEMO_ASK_STATE, str)
    }

    @Test
    fun parseAskState() {
        val buf = Unpooled.buffer().also { it.writeBytes(BcdString.toByteArray(DEMO_ASK_STATE)) }
        val p = D10Packet()
        assertTrue(p.parse(buf))

        lgr.info(JSON.toJSONString(p, true))
        assertEquals(FuncType.AskState, p.data?.type)
        val data = p.data as DtenAskStateData
        assertEquals(3.65F, data.volt)
        assertEquals(DateTime(2012, 11, 3, 10, 20, 32), data.time)
        assertArrayEquals(ByteArray(20) { 0 }, data.warnBcd?.hexArray)
    }

    companion object {
        private val lgr = LoggerFactory.getLogger(D10LoginDataTest::class.java)

        const val DEMO_STR = "49455344313012000001"

        const val DEMO_ASK_STATE = "6812000001231c121103102032036500000000000000000000000000000000000000005616"
    }
}